package com.tkp.entity;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.http.HttpStatus;

import java.io.Serializable;

/**
 * 返回信息
 * @author duk
 */
@Data
public class ResultCode<T> implements Serializable {

    private final static String MSG_ERROR = "未知错误";
    private final static String MSG_OK = "成功";
    private final HttpStatus code;
    private final String msg;
    private final T data;
    private final boolean success;

    private ResultCode(HttpStatus code, T data, String msg){
        this.code = code;
        this.data = data;
        this.msg = msg;
        this.success = code.is2xxSuccessful();
    }

    public static <T> ResultCode<T> getFailureNotLogin(){
        return getFailure(HttpStatus.INTERNAL_SERVER_ERROR, MSG_ERROR);
    }

    public static <T> ResultCode<T> getSuccess(){
        return getSuccessReturn(null);
    }

    public static <T> ResultCode<T> getSuccessReturn(T data){
        return getReturn(HttpStatus.OK, MSG_OK, data);
    }

    public static <T> ResultCode<T> getFailure(){
        return getFailure(HttpStatus.INTERNAL_SERVER_ERROR, MSG_ERROR);
    }

    public static <T> ResultCode<T> getFailure(String msg){
        return getFailure(HttpStatus.INTERNAL_SERVER_ERROR, msg);
    }
    public static <T> ResultCode<T> getFormatFailure(String msg,Object... value){
        return getFailure(HttpStatus.INTERNAL_SERVER_ERROR, StrUtil.format(msg,value));
    }

    public static <T> ResultCode<T> getFailure(HttpStatus code, String msg){
        return getReturn(code, msg, null);
    }

    public static <T> ResultCode<T> getReturn(HttpStatus code, String msg, T data){
        return new ResultCode<T>(code, data, msg);
    }

    public boolean isSuccess(){
        return success;
    }
    public int getCode(){
        return code.value();
    }
}
